package com.yanghx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author yangHX
 * createTime  2019/5/28 19:22
 */
public class LocalTranJdbcApplication {
    private static final Logger logger = LoggerFactory.getLogger(LocalTranJdbcApplication.class);


    public static void main(String[] args) throws SQLException {
        String plusAmountSQL = "UPDATE T_USER SET amount = amount+100 WHERE username =?";
        String minusAmountSQL = "UPDATE T_USER SET amount = amount-100 WHERE username =?";
        Connection dbConnection = getConnection();
        logger.debug("Begin");
        //取消自动提交
        dbConnection.setAutoCommit(false);
        PreparedStatement plusStatement = dbConnection.prepareStatement(plusAmountSQL);
        plusStatement.setString(1, "SuperMan");
        plusStatement.executeUpdate();


        PreparedStatement minusStatement = dbConnection.prepareStatement(minusAmountSQL);
        minusStatement.setString(1, "BatMan");
        minusStatement.executeUpdate();
        dbConnection.commit();
        logger.debug("Done!");
        plusStatement.close();
        minusStatement.close();
        dbConnection.close();
    }

    private static Connection getConnection() throws SQLException {
        String DB_DRIVER = "com.mysql.jdbc.Driver";
        String DB_CONNECTION = "jdbc:mysql://localhost:3306/dist_tran_course";
        String DB_USER = "root";
        String DB_PASSWORD = "root";
        try {
            Class.forName(DB_DRIVER);
        } catch (ClassNotFoundException e) {
            logger.error(e.getMessage());
        }
        return DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
    }


    private static void simulateError() throws SQLException {
        throw new SQLException("Simulate some error!");
    }

}
